package cn.lili.controller.store.other;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * @author YangHua
 * 转载请注明出处：http://www.xfok.net/2009/10/124491.html
 */
public class MyGmail {
   
    private String smtpHost = "smtp.gmail.com";
    private String smtpPort = "465";
    private String smtpAuth = "true";

    private String popHost = "pop.gmail.com";
    private String popPort = "995";
   
    private Multipart mp;

    public void send(String user, String pass, String to, String subject,
            String body) throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", smtpHost);
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);
        props.put("mail.smtp.auth", smtpAuth);
        final String username = user;
        final String password = pass;
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,
                false));
        msg.setSubject(subject);
        msg.setText(body);
        msg.setSentDate(new Date());
        Transport.send(msg);
        System.out.println("Message sent.");
    }
   
    public void send(String user, String pass, String to, String subject,
            String html,String affix) throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", smtpHost);
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);
        props.put("mail.smtp.auth", smtpAuth);
        final String username = user;
        final String password = pass;
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,
                false));
        msg.setSubject(subject);
        mp=new MimeMultipart();
        BodyPart bp = new MimeBodyPart();
        bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=gb2312>"
                        + html, "text/html;charset=UTF-8");
        mp.addBodyPart(bp);
        BodyPart bp1 = new MimeBodyPart();
        FileDataSource fileds = new FileDataSource(affix);
        bp1.setDataHandler(new DataHandler(fileds));
        bp1.setFileName(fileds.getName());
        mp.addBodyPart(bp1);
        msg.setSentDate(new Date());
        msg.setContent(mp);
        Transport.send(msg);
        System.out.println("Message sent.");
    }

    public void fetch(String username, String password) throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.pop3.socketFactory.fallback", "false");
        props.setProperty("mail.pop3.port", popPort);
        props.setProperty("mail.pop3.socketFactory.port", popPort);
        // 以下步骤跟一般的JavaMail操作相同
        Session session = Session.getDefaultInstance(props);
        // 请将红色部分对应替换成你的邮箱帐号和密码
        URLName urln = new URLName("pop3", popHost, Integer.parseInt(popPort),
                null, username, password);
        Store store = session.getStore(urln);
        Folder inbox = null;
        try {
            store.connect();
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            FetchProfile profile = new FetchProfile();
            profile.add(FetchProfile.Item.ENVELOPE);
            Message[] messages = inbox.getMessages();
            inbox.fetch(messages, profile);
            System.out.println("收件箱的邮件数：" + messages.length);
            for (int i = 0; i < messages.length; i++) {
                // 邮件发送者
                String from = decodeText(messages[i].getFrom()[0].toString());
                InternetAddress ia = new InternetAddress(from);
                System.out.println("FROM:" + ia.getPersonal() + '('
                        + ia.getAddress() + ')');
                // 邮件标题
                System.out.println("TITLE:" + messages[i].getSubject());
                // 邮件大小
                System.out.println("SIZE:" + messages[i].getSize());
                // 邮件发送时间
                System.out.println("DATE:" + messages[i].getSentDate());
            }
        } finally {
            try {
                inbox.close(false);
            } catch (Exception e) {
            }
            try {
                store.close();
            } catch (Exception e) {
            }
        }
    }

    protected static String decodeText(String text)
            throws UnsupportedEncodingException {
        if (text == null)
            return null;
        if (text.startsWith("=?GB") || text.startsWith("=?gb"))
            text = MimeUtility.decodeText(text);
        else
            text = new String(text.getBytes("ISO8859_1"));
        return text;
    }

    public static void main(String[] args) {
        MyGmail mg = new MyGmail();
        String user = "listgoo9898@gmail.com";
        String pass = "varfgchdeqmyfcgj";
        String to = user;
        String subject = "Subject";
        String body = "body";
        String html="<meta http-equiv=Content-Type content=text/html; charset=gb2312>"
            + "<div align=center><a href=http://www.xfok.net> xfok </a></div>";
        String affix="d://db//xfok.db";
        try {
            mg.send(user, pass, to, subject, body);
            mg.send(user, pass, to, subject, html, affix);
            mg.fetch(user, pass);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
